/** @description  **/
/** @author  wutao **/
/** @date 2020-04-20 **/
import Vue from 'vue';
import coordTrans from '@/common/openlayer/coordinate_transfor.js'
import permission from '@/common/lib/permission/permission.js'
let appInfo = {
	wgtCode: "0.0.0", //热更版本号
	wholeCode: "0.1.9" //全量包版本号
}

/** 
 * 比较版本大小，如果新版本nv大于旧版本ov则返回true，否则返回false 
 * @param {String} ov 
 * @param {String} nv 
 * @return {Boolean}  
 */
appInfo.compareVersion = (ov, nv) => {
	if (!ov || !nv || ov == "" || nv == "") {
		return false;
	}
	var b = false,
		ova = ov.split(".", 4),
		nva = nv.split(".", 4);
	for (var i = 0; i < ova.length && i < nva.length; i++) {
		var so = ova[i],
			no = parseInt(so),
			sn = nva[i],
			nn = parseInt(sn);
		if (nn > no || sn.length > so.length) {
			return true;
		} else if (nn < no) {
			return false;
		}
	}
	if (nva.length > ova.length && 0 == nv.indexOf(ov)) {
		return true;
	}
}
appInfo.compareVersionCode = (oldCode, newCode) => {
	try {
		return parseInt(newCode) > parseInt(oldCode)
	} catch (e) {
		//TODO handle the exception
		return false
	}

}

appInfo.getSysInfo = () => {
	let systemInfo = uni.getSystemInfoSync();
	// console.log(systemInfo)
	return systemInfo
}

appInfo.getAppInfo = () => {
	return new Promise((resolve, reject) => {
		plus.runtime.getProperty(plus.runtime.appid, function(inf) {
			var old = inf.version;
			// console.log(inf)
			resolve(inf);
		});
	})

}

//安装app
appInfo.installApk = (path, callBack, errorCallBack) => {
	plus.runtime.install(path, {}, callBack, errorCallBack);
}
/* 检查更新 */
appInfo.updateCheck = () => {
	console.log('updateCheck');
	let wgtCode = appInfo.wgtCode;
	let wholeCode = appInfo.wholeCode;
	let newWgtCode;
	let newWholeCode;
	let params = {};
	let updataInfo;

	return new Promise((resolve, reject) => {

		//获取当前版本号 等信息
		let platform = appInfo.getSysInfo().platform.toLowerCase();
		let opt = Vue.prototype.$appApi.getApi('updateCheck', params, true, false);
		//请求
		let reqeust = Vue.prototype.$tools.request(
			opt,
			result => {
				console.log(result);
				if (!result) {
					resolve(false);
					return
				}
				newWgtCode = result.wgtCode;
				newWholeCode = result.wholeCode;
				updataInfo = result;
				updataInfo['platform'] = platform;
				// 是否有整包更新
				if (appInfo.compareVersion(wholeCode, newWholeCode)) {
					console.log('整包更新');
					updataInfo['type'] = 'whole';
					let url =
						'/components/update-check/update-check' +
						Vue.prototype.$u.queryParams(updataInfo);
					uni.navigateTo({
						url: url
					});
					resolve(true);
				} else {
					// 是否有热更新
					if (appInfo.compareVersion(wgtCode, newWgtCode)) {
						console.log('热更新');
						updataInfo['type'] = 'wgt';
						let url =
							'/components/update-check/update-check' +
							Vue.prototype.$u.queryParams(updataInfo);
						uni.navigateTo({
							url: url
						});
						resolve(true);
					} else {
						//没有更新
						resolve(false);
					}
				}
			},
			error => {
				reject();
			}
		);
	});

}
//双击退出
let isFirst = null;
appInfo.onBackPressQuit = (title) => {

	if (!isFirst) {
		isFirst = new Date().getTime();
		uni.showToast({
			title: title,
			duration: 2000,
			position: 'bottom'
		});
		setTimeout(() => {
			isFirst = null;

		}, 2000);
	} else {
		if (new Date().getTime() - isFirst < 2000) {
			plus.runtime.quit();
		}
	}
}
// 设置应用数字角标
appInfo.setBadgeNum = (count) => {
	plus.runtime.setBadgeNumber(count);
}
/* 压缩图片 */
appInfo.compressImage = (src, quality = 68) => {
	let dst = '_compress/' + appInfo.uuidGenerator() + src.substring(src.lastIndexOf('.'));
	console.log(dst);
	return new Promise((resolve, reject) => {
		plus.zip.compressImage({
				src: src,
				dst: dst,
				quality: quality,
				overwrite: true
			},
			function(e) {
				console.log(e);
				resolve({
					result: true,
					picPath: e.target
				})
			},
			function(error) {
				console.log(error);
				reject({
					result: false,
					picPath: e.target
				})
			});

	});
}
appInfo.uuidGenerator = () => {
	var originStr = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
		originChar = '0123456789abcdef',
		len = originChar.length;
	return originStr.replace(/x/g, function(match) {
		return originChar.charAt(Math.floor(Math.random() * len));
	});
}
/* 定位 */
appInfo.onMyLocation = (success, fail, coordsType = 'bd09ll') => {
	console.log('onMyLocation', );
	if (!permission.checkSystemEnableLocation()) {
		uni.showModal({
			title: '需要开启系统定位服务',
			content: '用于提供精确的定位、导航类服务',
			confirmText: '我知道了',
			success: (res) => {
				if (res.confirm) {
					permission.gotoLoactionManagerSetting();
				}
			}
		});
		return;
	}
	plus.geolocation.getCurrentPosition(res => {
		// console.log(res);
		if(coordsType == 'wgs84'){
			let a = coordTrans.baiduTomars(res.coords.latitude, res.coords.longitude);
			let wgs84 = coordTrans.gcj_decrypt(a.lat, a.lon);
			res.coords.latitude = wgs84.lat;
			res.coords.longitude = wgs84.lon;
		}
		typeof success === 'function' && success(res);

	}, error => {
		console.log(error);
		uni.showToast({
			title: '定位失败，错误码:' + error.message,
			icon: 'none',
			position: 'bottom'
		})
		typeof fail === 'function' && fail(error);
	}, {
		provider: 'baidu',
		timeout: 5000,
		enableHighAccuracy: true,
		coordsType: 'bd09ll',
		geocode: true
	})

}
//dst, det, dstName, detName 起点 终点   起点名称  终点名称
appInfo.toNavigation = (dst, det, dstName, detName) => {
	let platform = appInfo.getSysInfo().platform;
	let maps, asList, destination, origin, url = null;
	if (platform === 'ios') {
		maps = [{
				title: '苹果地图',
				has: true
			}, {
				title: '高德地图',
				has: plus.runtime.isApplicationExist({
					pname: 'com.autonavi.minimap',
					action: 'iosamap://'
				})
			}, {
				title: '百度地图',
				has: plus.runtime.isApplicationExist({
					pname: 'com.baidu.BaiduMap',
					action: 'baidumap://'
				})

			}

		];

		//过滤可用的第三方地图
		asList = maps.filter(e => {
			return e.has
		});
		uni.showActionSheet({
			itemList: asList.map(e => {
				return e.title
			}),
			success: res => {
				switch (asList[res.tapIndex].title) {
					case '苹果地图':
						//苹果地图
						destination = new plus.maps.Point(det[0], det[1]); // 目的地
						origin = new plus.maps.Point(dst[0], dst[1]); // 起点
						console.log('目的地' + det, '起点' + dst);
						plus.maps.openSysMap(destination, "地块导航", origin);
						break;
					case '高德地图':
						//高德地图
						origin = '&slat=' + dst[1] + '&slon=' + dst[0] + '&sname=' + dstName;
						destination = '&dlat=' + det[1] + '&dlon=' + det[0] + '&dname=' + detName;;
						url = 'iosamap://path?sourceApplication=' + '智慧明珠' + origin + destination +
							'&dev=1';
						plus.runtime.openURL(encodeURI(url),
							error => {
								console.log(error);
							});
						break;
					case '百度地图':
						//百度地图
						origin = dst[1] + ',' + dst[0];
						destination = det[1] + ',' + det[0];
						url =
							'baidumap://map/direction?origin=' + 'name:' + dstName + '|' +
							'latlng:' + origin + '&destination=' + 'name:' + detName + '|' +
							'latlng:' + destination +
							'&coord_type=wgs84&mode=driving&src=com.ym.yilimz';
						plus.runtime.openURL(encodeURI(url), error => {
							console.log(error);
						});
						break;

				}
			}
		});
	} else if (platform === 'android') {
		maps = [{
				title: '百度地图',
				has: plus.runtime.isApplicationExist({
					pname: 'com.baidu.BaiduMap',
					action: 'baidumap://'
				})

			},
			{
				title: '高德地图',
				has: plus.runtime.isApplicationExist({
					pname: 'com.autonavi.minimap',
					action: 'androidamap://'
				})
			}
		];
		//过滤可用的第三方地图
		asList = maps.filter(e => {
			return e.has
		});
		if (asList && asList.length == 0) {
			uni.showModal({
				title: '请先安装百度地图或者高德地图'
			})
			return;
		}
		//打开选择弹窗
		uni.showActionSheet({
			itemList: asList.map(e => {
				return e.title
			}),
			success: res => {
				switch (asList[res.tapIndex].title) {
					case '百度地图':
						//百度地图
						origin = dst[1] + ',' + dst[0];
						destination = det[1] + ',' + det[0];
						url =
							'baidumap://map/direction?origin=' + 'name:' + (dstName || '') + '|' +
							'latlng:' + origin + '&destination=' + 'name:' + detName + '|' +
							'latlng:' + destination +
							'&coord_type=wgs84&mode=driving&src=com.ym.yilimz';
						plus.runtime.openURL(encodeURI(url), error => {
							console.log(error);
						});
						break;
					case '高德地图':
						//高德地图
						origin = '&slat=' + dst[1] + '&slon=' + dst[0] + '&sname=' + dstName;
						destination = '&dlat=' + det[1] + '&dlon=' + det[0] + '&dname=' + detName;;
						url = 'amapuri://route?sourceApplication=' + '智慧明珠' + origin + destination +
							'&dev=1';
						plus.runtime.openURL(encodeURI(url),
							error => {
								console.log(error);
							});
						break;
				}
			}
		})
	} else {

	}
}


export default appInfo
